#include "normal_com.h"
int search_precode(int code){//查找到前一个code
    char query[100]={0};
    char result[100]={0};
    sprintf(query,"select precode from FileList where code = '%d';",code);
    search_from_database(query,result);
    return atoi(result);
}
int search_code(char* c){//查找到前一个code
    char query[100]={0};
    char result[100]={0};
    sprintf(query,"select code from FileList where filename = '%s';",c);
    search_from_database(query,result);
    return atoi(result);
}
void display_path(char* path,int new_fd,train_t* nt){
    int i=0;
    char final_path[200]={0};
    char filename[50];
    for(;path[i]!=0;i++);
    int len_of_filename=0;
    for(;i>=0;i--){
        bzero(filename,sizeof(filename));
        char query[100]={0};
        sprintf(query,"select filename from FileList where code = '%d';",path[i]);
        search_from_database(query,filename);
        strncpy(final_path+len_of_filename,filename,strlen(filename));
        len_of_filename+=strlen(filename);
    }
    bzero(nt,sizeof(train_t));
    nt->data_len=strlen(final_path);
    strcpy(nt->buf,final_path);
    send_n(new_fd,&nt->data_len,4);
    send_n(new_fd,nt->buf,nt->data_len);
}
void do_ls(pClient_State_t CS,train_state_t* pt,train_t* nt) {//只支持ls当前目录下的所有文件
    char c[5]={0};
    int precode;
    char query[100]={0};
    char result[100]={0};
    if(strcmp(pt->buf,c)==0){
        precode=search_precode(CS->code);
        printf("code=%d\n",CS->code);
        sprintf(query,"select filename from FileList where precode = '%d';",CS->code);
        search_from_database(query,result); 
        nt->data_len=strlen(result);
        int rrs=send_n(CS->new_fd,&nt->data_len,4);
        strcpy(nt->buf,result);
        rrs=send_n(CS->new_fd,nt->buf,nt->data_len);
    }else{
    }
}
void do_cd(pClient_State_t CS,train_state_t* pt,train_t* nt) {//cd .. / 目录
    char path[20];
    int code=CS->code;
    int precode=search_precode(CS->code);
	if(strcmp(pt->buf,"..")==0){//找到表中code所在列，然后取出precode
        CS->code=precode;
        code=precode;
    }else if(strcmp(pt->buf,"/")==0){
        CS->code=0;
        code=0;
    }else {
        CS->code=search_code(pt->buf);
        code=CS->code;
    }
    int i=0;
    for(;code!=-1;i++){
        path[i]=code;
        code=search_precode(code);
    }
    display_path(path,CS->new_fd,nt);
}
//通过getcwd拿到当前路径，并发送给客户端
void do_pwd(pClient_State_t CS,train_state_t* pt,train_t* nt) {
    char path[20];
	int code=CS->code;
    int i=0;
    for(;code!=-1;i++){
        path[i]=code;
        code=search_precode(code);
    }
    display_path(path,CS->new_fd,nt);
}
void do_remove(pClient_State_t CS,train_state_t* pt,train_t* nt) {//移除当前目录下的某个文件
    char query[100]={0};
    sprintf(query,"delete from FileList where filename = '%s';",pt->buf);
    delete_insert_updata(query);           
}